package behavioralPatterns.mediator;

import java.util.ArrayList;
import java.util.List;

interface Colleague {
    void send(String msg);

    void receive(String msg);
}

class ConcreteColleague implements Colleague {

    private String name;
    private Mediator mediator;

    public ConcreteColleague(String name, Mediator mediator) {
        this.name = name;
        this.mediator = mediator;
        mediator.register(this);
    }

    @Override
    public void send(String msg) {
        mediator.send(msg, this);
    }

    @Override
    public void receive(String msg) {
        System.out.println("Colleague " + name + " received " + msg);
    }
}

interface Mediator {
    void register(Colleague colleague);

    void send(String msg, Colleague colleague);
}

class ConcreteMediator implements Mediator {
    private List<Colleague> colleagues;

    public ConcreteMediator() {
        colleagues = new ArrayList<>();
    }

    @Override
    public void register(Colleague colleague) {
        colleagues.add(colleague);
    }

    @Override
    public void send(String msg, Colleague colleague) {
        for (Colleague c : colleagues) {
            if (c != colleague) {
                c.receive(msg);
            }
        }
    }
}

public class MediatorPattern {
    public static void main(String[] args) {
        Mediator mediator = new ConcreteMediator();
        Colleague colleague1 = new ConcreteColleague("Colleague1", mediator);
        Colleague colleague2 = new ConcreteColleague("Colleague2", mediator);
        Colleague colleague3 = new ConcreteColleague("Colleague3", mediator);

        colleague1.send("Hello");
        colleague2.send("World");
        colleague3.send("!");
    }
}
